<?php
namespace app\install\controllers;

use app\models\AdminRecorder;

class CheckController extends BaseController{

    public function actionCheck(){
        $type = \Yii::$app->request->post('type');
        $base = str_replace("web/index.php","",$_SERVER["PHP_SELF"]);
        $arr=[];
        $arr['is'] = 1;
        switch(intval($type)){
            case 1://php 版本
                if(PHP_VERSION<7.3){
                    $arr['is'] = 0;
                }
                $arr['info'] = "PHP版本：".PHP_VERSION;
                break;
            case 2://
                if(!extension_loaded('gd')||!function_exists('imagecreate')){
                    $arr['is']=0;
                }
                $arr['info']="GD库";
                break;
            case 3:
                if(!$this->check_dir_write("../config/")){
                    $arr['is']=0;
                }
                $arr['info'] = "config目录可写";
                break;
            case 4:
                if(!$this->check_dir_write("../web/upload/")){
                    $arr['is']=0;
                }
                $arr['info'] = "upload目录可写";
                break;
        }
        $result = ['result'=>1,'data'=>$arr];
        return json_encode($result,JSON_NUMERIC_CHECK);
    }


    public function actionDb(){
        $post = \Yii::$app->request->post('form');
        $is_web = intval(\Yii::$app->request->post('is_web'));
        $host = $post['host'];//主机名
        $username = $post['username'];//用户名
        $password = $post['password'];//密码
        $tablePrefix = $post['tablePrefix'];//表前缀
        $db_name = $post['db_name'];//表名
        $admin = $post['admin'];//目录名
        $url = $post['url'];//安装地址
        if(empty($host)){
            $result = ['result'=>0,'data'=>'请输入主机地址'];
            return json_encode($result);
        }
        if(empty($username)){
            $result = ['result'=>0,'data'=>'请输入用户名'];
            return json_encode($result);
        }
        if(empty($password)){
            $result = ['result'=>0,'data'=>'请输入密码'];
            return json_encode($result);
        }
        $tablePrefix = empty($tablePrefix)?"shop_":$tablePrefix;
        if(empty($db_name)){
            $result = ['result'=>0,'data'=>'请输入数据库名'];
            return json_encode($result);
        }
        if(empty($admin)){
            $result = ['result'=>0,'data'=>'请输入后台目录名'];
            return json_encode($result);
        }
        if(empty($url)){
            $result = ['result'=>0,'data'=>'请输入安装地址'];
            return json_encode($result);
        }
        $con = @mysqli_connect($host,$username,$password,$db_name);
        if(!$con){
            $result = ['result'=>0,'data'=>mysqli_connect_error()];
            return json_encode($result);
        }

        $config = "<?php
return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host={$host};dbname={$db_name}',
    'username' => '{$username}',
    'password' => '{$password}',
    'charset' => 'utf8',
    'tablePrefix' => '{$tablePrefix}',
];";
        $is_write = file_put_contents("../config/db.php",$config);
        if(!$is_write){
            $result = ['result'=>0,'data'=>'配置文件错误，请检查config是否有读写权限'];
            return json_encode($result);
        }
        $sql_file = file_get_contents("../install/data/data.sql");
        $sql_arr = explode(";\n",$sql_file);

        $i_sql=[];//演示数据
        foreach($sql_arr as $v){
            if(empty($v)){
                continue;
            }
            $v = str_replace("shop_",$tablePrefix,$v);
            if(stristr($v,"INSERT INTO")){
                $i_sql[]=$v;
            }else{
                $res = @mysqli_query($con,$v);
                if(!$res){
                    $result = ['result'=>0,'data'=>mysqli_error($con)];
                    return json_encode($result);
                }
            }
        }

        if(intval($post['is'])){
            foreach($i_sql as $v){
                $res = @mysqli_query($con,$v);
                if(!$res){
                    $result = ['result'=>0,'data'=>mysqli_error($con)];
                    return json_encode($result);
                }

            }
        }

        $config_sql = "SELECT content FROM ".$tablePrefix."set WHERE set_type=1";
        $res = @mysqli_query($con,$config_sql);
        $row=mysqli_fetch_assoc($res);
        if(!empty($row['content'])){
            $row['content'] = json_decode($row['content'],true);
            $row['content']['base_url'] = $url;
            $sql = "UPDATE ".$tablePrefix."set SET content=".$row['content']." WHERE set_type=1";
        }else{
            $content['base_url'] = $url;
            $content = json_encode($content);
            $sql = "INSERT INTO ".$tablePrefix."set (content,updatetime,set_type) VALUES ('{$content}','".time()."',1)";
        }
        @mysqli_query($con,$sql);


        $admin_dir = $admin."/";
        @mkdir($admin_dir);
        $old_admin_dir="../install/admin/";
//        $http_url = $is_web?$url:$url."web/";
        $this->copy($admin_dir,$old_admin_dir,$url,$admin);

        $result = ['result'=>1,'data'=>'操作完成',"admin"=>$admin,"url"=>$url];
        return json_encode($result);

    }


    public function actionGeturl(){
        $is_web = intval(\Yii::$app->request->post('is_web'));
        $result = ['result'=>1,'data'=>$this->url($is_web)];
        return json_encode($result);
    }

    public function url($is_web=0){
        $url_dir = \Yii::$app->request->getBaseUrl();
        $url_dir = $is_web?str_replace("web","",$url_dir):$url_dir;
        $url = \Yii::$app->request->getHostInfo();
        $url.=$url_dir.'/';
        return $url;
    }



    public function copy($new_dir,$old_dir,$url,$admin){
        $hand = opendir($old_dir);
        while($file=readdir($hand)){
            if($file=="."||$file==".."){
                continue;
            }
            if(is_dir($old_dir.$file)){
                @mkdir($new_dir.$file);
                $this->copy($new_dir.$file."/",$old_dir.$file."/",$url,$admin);
            }else{
                copy($old_dir.$file,$new_dir.$file);
                if($file=="app.js"){
                    $f_content = file_get_contents($new_dir.$file);
                    $f_content = str_replace("{{url}}",$url,$f_content);
                    file_put_contents($new_dir.$file,$f_content);
                }
//                if($file=="css.css"){
//                    $f_content = file_get_contents($new_dir.$file);
//                    $f_content = str_replace("{{url}}",$url.$admin,$f_content);
//                    file_put_contents($new_dir.$file,$f_content);
//                }
                if($file=="index.html"){
                    $f_content = file_get_contents($new_dir.$file);
                    $f_content = str_replace("/beesshop",$url.$admin,$f_content);
                    file_put_contents($new_dir.$file,$f_content);
                }
            }
        }
    }



    public function actionUser(){
        $post = \Yii::$app->request->post('form');
        $is_web = intval(\Yii::$app->request->post('is_web'));
        $admin_name = $post['admin_name'];
        $admin_password = $post['admin_password'];
        $admin_password2 = $post['admin_password2'];
        if(empty($admin_name)){
            $result = ['result'=>0,'data'=>'请填写管理员名'];
            return json_encode($result);
        }
        if(empty($admin_password)){
            $result = ['result'=>0,'data'=>'请填写密码'];
            return json_encode($result);
        }
        if(empty($admin_password2)){
            $result = ['result'=>0,'data'=>'请填写确认密码'];
            return json_encode($result);
        }
        if($admin_password2!==$admin_password){
            $result = ['result'=>0,'data'=>"两次输入密码不一样"];
            return json_encode($result);
        }
        AdminRecorder::deleteAll();
        $model = new AdminRecorder();
        $model->admin_name = $admin_name;
        $model->admin_password = \Yii::$app->security->generatePasswordHash($admin_password);
        $model->addtime = time();
        $model->updatetime = time();
        $model->save(false);
        //生成lock
        @mkdir("../data");
        @file_put_contents("../data/install.lock",$is_web);
        $this->del("../install/");
        $result = ['result'=>1,'data'=>'操作成功'];
        return json_encode($result);
    }


    public function actionDel(){
        $is = \Yii::$app->request->post('is');
        $result = ['result'=>1,'data'=>'操作成功'];
        return json_encode($result);
    }


    public function del($dir){
        $h = opendir($dir);
        while($file=readdir($h)){
            if($file=="."||$file==".."){
                continue;
            }
            if(is_dir($dir.$file)){
                if($this->del($dir.$file."/")){
                    @rmdir($dir.$file);
                }
                
            }else{
                @unlink($dir.$file);
            }
        }
        return 1;
    }

}
